package com.zym.init.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zym.init.exception.ServiceException;
import com.zym.init.model.bo.LoginUser;
import com.zym.init.model.po.PermissionPo;
import com.zym.init.model.po.RolePo;
import com.zym.init.model.po.UserPo;
import com.zym.init.service.PermissionService;
import com.zym.init.service.RoleService;
import com.zym.init.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    final private UserService userService;
    final private RoleService roleService;
    final private PermissionService permissionService;

    public UserDetailsServiceImpl(UserService userService, RoleService roleService, PermissionService permissionService) {
        this.userService = userService;
        this.roleService = roleService;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPo::getUsername, username);
        wrapper.eq(UserPo::getIsDeleted, false);
        UserPo userPo = userService.getOne(wrapper);

        if (Objects.isNull(userPo)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("用户名或密码错误");
        }

        List<RolePo> rolePoList = new ArrayList<>();

        // 加载用户角色
        if (userPo.getRoleList() != null && !userPo.getRoleList().isEmpty()) {
            QueryWrapper<RolePo> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.in("role_code", userPo.getRoleList());
            rolePoList = roleService.list(roleQueryWrapper);
        }

        Set<String> permissionList = new HashSet<>();

        // 加载用户权限
        for (RolePo rolePo : rolePoList) {
            if (rolePo.getPermissionList() != null && !rolePo.getPermissionList().isEmpty()) {
                QueryWrapper<PermissionPo> permissionQueryWrapper = new QueryWrapper<>();
                permissionQueryWrapper.in("permission_code", rolePo.getPermissionList());
                List<PermissionPo> list = permissionService.list(permissionQueryWrapper);
                permissionList.addAll(list.stream().map(PermissionPo::getPermissionCode).toList());
            }
        }

        log.info("当前登录用户：{} 角色：{}，权限：{}", username, rolePoList, permissionList);
        return new LoginUser(userPo.getUserId(), userPo, permissionList);
    }
}
